#include "aed_image.h"


#include <Windows.h>
#include <gl/Gl.h>
#include <gl\glu.h>			// Header File For The GLu32 Library

#include <QDomElement>
#include <QStringList>
#include <QDebug>

#include "soil/SOIL.h"
//#include "AIO_Image.hpp"
//#include "..\utils\AK_Utils.hpp"






AED_Image::AED_Image():m_loaded(false),m_name("NONAME"),m_x_div(1),m_y_div(1){}

AED_Image::~AED_Image(){
    Free();
}

QString AED_Image::GetName() const{
    return m_name;
}

QString AED_Image::GetPath() const{
    return m_path;
}

void AED_Image::SetPath(const QString &path){
    m_path = path;
}

void AED_Image::SetName(const QString &name){
    m_name = name;
}

int AED_Image::GetXDiv() const{
    return m_x_div;
}
int AED_Image::GetYDiv() const{
    return m_y_div;
}

int AED_Image::Load(const QString  &filename){

    QByteArray ba = filename.toLocal8Bit();
    const char *c_str = ba.data();
    m_texname = SOIL_load_OGL_texture
        (
            c_str,
            0,
            SOIL_CREATE_NEW_ID,
            SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT
        );


    glBindTexture(GL_TEXTURE_2D, m_texname);

    m_path = filename;
    QStringList split = m_path.split("/");
    m_name = split.back();

    glGetTexLevelParameteriv(GL_TEXTURE_2D,  0, GL_TEXTURE_WIDTH,  &m_width);
    glGetTexLevelParameteriv(GL_TEXTURE_2D,  0, GL_TEXTURE_HEIGHT,  &m_height);

        /*TGA_file_header header;
        unsigned long Bread,err,size;
        const char *file;
        HANDLE infile;
        SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES),NULL,TRUE};

        m_path = filename;
        QStringList split = m_path.split("/");
        m_name = split.back();

        file=filename.toAscii().data();

        infile=CreateFileA(file,GENERIC_READ,NULL,&sa,OPEN_EXISTING,0,NULL);
        if ((int)infile < 0){
                //cerr << "Could not open the tga file " << filename << endl;
                return 0;
        }

        err=ReadFile(infile,&header,sizeof(header),(LPDWORD)&Bread,NULL);
        if (err==0){
                //cerr << "Could not read the TGA header" << endl;
                return 0;
        }

        m_width=header.Width;
        m_height=header.Height;
        m_depth=header.Image_pixel_size;

    int bytes = header.Image_pixel_size/8;
    size=bytes*header.Height*header.Width;

    pixel_array=new GLubyte[size];
    GLubyte *pixel_arrayRGBA;
    err=ReadFile(infile,pixel_array,size,(LPDWORD)&Bread,NULL);
    if (err == 0){
            //cerr << "Could not read the pixel field" << endl;
            return 0;
     }
    if (bytes == 4){// pixel size = 32b
        pixel_arrayRGBA=new GLubyte[size];
        for (int i=0;i<size;i+=bytes){//Qt BGRA - OpenGL RGBA
            pixel_arrayRGBA[i]=pixel_array[i+2];
            pixel_arrayRGBA[i+1]=pixel_array[i+1];
            pixel_arrayRGBA[i+2]=pixel_array[i];
            pixel_arrayRGBA[i+3]=pixel_array[i+3];
        }

    }
    else if (bytes == 3){ // Qt RGB - OpenGL RGB
        GLubyte* aux = new GLubyte[bytes];
        for(int i=0; i<size;i+=bytes){
            for(int j=0; j<bytes;j++)
                aux[j] = pixel_array[i+j];
            pixel_array[i]=aux[2];
            pixel_array[i+2]=aux[0];
        }
        delete aux;
    }


    glGenTextures(1, &m_texname);
    glBindTexture(GL_TEXTURE_2D, m_texname);


    switch(bytes){
    case 1:
        glTexImage2D(GL_TEXTURE_2D,0, GL_LUMINANCE, m_width, m_height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, pixel_array);
        format=QImage::Format_Mono;
        //qDebug()<<"Format_Mono";
        break;
    case 3:
        glTexImage2D(GL_TEXTURE_2D,0, bytes, m_width, m_height, 0, GL_RGB, GL_UNSIGNED_BYTE, pixel_array);
        format=QImage::Format_RGB888;
       //qDebug()<<"Format_RGB888";
        break;
    case 4:
        glTexImage2D(GL_TEXTURE_2D,0, bytes, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixel_arrayRGBA);
        format=QImage::Format_ARGB32;
        //qDebug()<<"Format_ARGB32";
        delete [] pixel_arrayRGBA;
        break;
    default:
        //delete [] pixel_array;
        //cerr << "Bad Tex Format" << endl;
        break;
    }

        //delete [] pixel_array;
        CloseHandle(infile);

    m_loaded = true;


    */



    QImage image;
    bool loaded = image.load(filename);

    /*if(loaded){
        m_width = image.width();
        m_height = image.height();
    }*/
    //QImage mirrored=image.mirrored(false,true);
    m_pixmap = QPixmap::fromImage(image);



    return 1;

}

short AED_Image::GetWidth() const{
    return m_width;
}

short AED_Image::GetHeight() const{
    return m_height;
}

GLuint AED_Image::GetTexName() const{
    return m_texname;
}


int AED_Image::Free(){
    if(!m_loaded){
        return 0;
    }

    glDeleteTextures(1, &m_texname);
    delete [] pixel_array;
    m_loaded = false;
    return 1;

}

/*int AIO_Image::Parse(const AIO_XMLToken &token){
    if(token.Name()=="path"){
        Load(token.Value());
    }else if(token.Name()=="name"){
        SetName(token.Value());
    }else if(token.Name()=="x_div"){
        m_x_div = String2Int(token.Value());
    }else if(token.Name()=="y_div"){
        m_y_div = String2Int(token.Value());
    }else{
        return 0;
    }

    return 1;
}*/

void AED_Image::Save(QTextStream &file){
    file << "<image>" << endl;
    file << "   <path = " << m_path << ">" << endl;
    file << "   <name = " << m_name << ">" << endl;
    file << "   <x_div = " << m_x_div << ">" << endl;
    file << "   <y_div = " << m_y_div << ">" << endl;
    file << "</image>"<<endl<<endl<<endl;
}

void AED_Image::Save(QDomDocument &doc, QDomElement &header, const QString &scenePath){
    QDomElement elem = doc.createElement("image");

    elem.setAttribute("path",m_path);
    elem.setAttribute("name",m_name);
    elem.setAttribute("x_div",m_x_div);
    elem.setAttribute("y_div",m_y_div);

    header.appendChild(elem);
}

bool AED_Image::Load(QDomElement &elem){
    if(elem.nodeName()!="image")
        return false;

    m_path = elem.attribute("path");
    m_name = elem.attribute("name");
    m_x_div = elem.attribute("x_div").toInt();
    m_y_div = elem.attribute("y_div").toInt();

    return true;
}

QPixmap AED_Image::ToPixmap(){

    return m_pixmap;
}

void AED_Image::Reload(){
    Load(m_path);
}
